package lab1;
import java.io.IOException;
import java.io.OutputStream;

/*
 *Evolution of the class.
 *I am assuming that more is going to be done with this class.
 *transfering html files etc. It is assumed that it will eventually
 *have to spawn a worker to handle the writing and one for reading.
 *Eventually have to take arrays and buffer data. May be advantagous
 *to create a simple jave object in the nature of a union that will hold a 
 *byte and int or a byte array. so that the worker can just use semaphores
 *and sometype of buffer to handle the writing. Hopefully. 
*/


public class ASCIIProtcolServer
{
	private OutputStream stream = null;
	
	public OutputStream getStream()
	{
		return stream;
	}

	public void setStream(OutputStream stream) throws IOException
	{
		if(this.stream == null ||
				this.stream != stream)
		{
			this.stream.flush();
			this.stream.close();
			this.stream = stream;
		}
		else
		{
			//continue, trying to set the stream to the same stream
		}
	}

	public static int byteToUnsignedInt (byte b)
	{
		int i = b;//could do it by casting but i think that this is more readable.
		return (i > 0? i : i + 256);
	}
	
	public static void checkedWrite (OutputStream out, byte b) throws IOException
	{
		out.write(ASCIIProtcolServer.byteToUnsignedInt(b));
	}

	public static void checkedWrite(OutputStream out, int i) throws IOException
	{
		ASCIIProtcolServer.checkedWrite(out, (byte) i);
	}
	
	public static void writeRoutine (OutputStream out) throws IOException 
	//just a test method for the first lab. print a rotating line of the printable ascii chars
	{
		int firstPrintableCharacter   = 33;
		int numberofPrintableCharacters = 94;
		int numberofCharactersPerLine   = 72;
		byte line = 0;

		int start = firstPrintableCharacter;
		while (line < 23) 
		{
			 for (int i = start; i < start+numberofCharactersPerLine; i++) 
			 {
				 ASCIIProtcolServer.checkedWrite(out, (byte)((i-firstPrintableCharacter) % numberofPrintableCharacters)+ 
						firstPrintableCharacter);
			 }
			 
			 ASCIIProtcolServer.checkedWrite(out, (byte)'\r');
			 ASCIIProtcolServer.checkedWrite(out, (byte)'\n');
			 
			start = ((start+1) - firstPrintableCharacter)
				 % numberofPrintableCharacters + firstPrintableCharacter;
			
			line++;
		}
	}
	
	public void checkedWrite (byte b) throws IOException
	{
		 ASCIIProtcolServer.checkedWrite(this.stream, b);
	}
	
	public void checkedWrite (int b) throws IOException
	{
		 ASCIIProtcolServer.checkedWrite(this.stream, b);
	}
	
	public ASCIIProtcolServer (OutputStream out)
	{
		this.stream = out;
	}
}
